package logic

import (
	"2103A-server/file/file"
	"2103A-server/file/internal/svc"
	"bytes"
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileUploadLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFileUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileUploadLogic {
	return &FileUploadLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FileUploadLogic) FileUpload(in *file.Request) (*file.Response, error) {
	// todo: add your logic here and delete this line

	bucket := "2103a-go"
	host := "http://rwhn5da2a.hd-bkt.clouddn.com/"
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac("z6BH7AEcZltkZlff9E3Qtv7-LaRxZVnpjtCxo78H", "CqkG-Lj4AD6TaNbh8qLqtuyDR41U1tX7yifQsMa-")
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Region = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{}

	dataLen := int64(len(in.FileContent))
	err := formUploader.Put(context.Background(), &ret, upToken, in.FileName, bytes.NewReader(in.FileContent), dataLen, &putExtra)
	if err != nil {
		fmt.Println(err)
		return &file.Response{
			Code:    "2001",
			Message: "上传失败",
			Path:    "",
		}, nil
	}
	fmt.Println(ret.Key, ret.Hash)

	return &file.Response{
		Code:      "200",
		Message:   "上传成功",
		Path:      host + ret.Key,
		WaterPath: host + ret.Key + "-water",
	}, nil
}
